package dao;



import exception.NotMatchException;

import java.sql.*;
import javax.swing.JOptionPane;


final class Dao {
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String dbUrl = "jdbc:mysql://127.0.0.1:3306/grade_management";
    private static final String dbUser = "root";
    private static final String dbPwd = "";
    private static Connection conn = null;

    static {
        try {
            if (conn == null) {
                Class.forName(driver).newInstance();
                conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null,
                    "数据库连接异常！");
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Dao() {
    }

    public static Connection getConnection() {
        if (conn == null) {
            throw new IllegalStateException("Connection has not been initialized yet！");
        }
        return conn;
    }

    public static boolean checkFieldExist(String tableName, String fieldName, String fieldValue) throws SQLException {
        boolean isExist = false;
        String sql = "select * " +
                "from " + tableName + " " +
                "where " + fieldName + "='" + fieldValue + "'";

        PreparedStatement stmt = conn.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            isExist = true;
        }

        return isExist;
    }

    public static void checkMatch(String sno, String sname, String cname) throws Exception {
        //1.检查学号是否存在
        //2.检查姓名是否和学号对应
        //3.检查学生是否选择了课程
        String sql1 = "select s_no,s_name from student where s_no=?";
        PreparedStatement stmt1 = conn.prepareStatement(sql1);
        stmt1.setString(1, sno);
        ResultSet rs1 = stmt1.executeQuery();
        if (rs1.next()) {
            String sname1 = rs1.getString(rs1.findColumn("s_name"));
            if (!sname1.equals(sname)) {
                throw new NotMatchException("学号和姓名不一致");
            }
        } else {
            throw new NotMatchException("不存在的学号");
        }

        String sql2 = "select * from choose_course where s_no=? and c_name=?";
        PreparedStatement stmt2 = Dao.getConnection().prepareStatement(sql2);
        stmt2.setString(1, sno);
        stmt2.setString(2, cname);
        ResultSet rs2 = stmt2.executeQuery();
        if (!rs2.next()) {
            throw new NotMatchException("学生没有选择此课程");
        }
    }

}